<template>
  <div class="flex time-date-picker">
    <el-date-picker
      v-model="date"
      align="right"
      type="date"
      placeholder="选择日期"
      :picker-options="datePickerOptions"
      value-format="yyyy-MM-dd"
    />
    <div
      v-if="date"
      class="time-selector flex"
    >
      <el-time-select
        v-model="startTime"
        style="width: 120px;"
        placeholder="起始时间"
        :picker-options="{
          start: getTimeSelectStartTime,
          step: step,
          end: end
        }"
      />
      <div style="margin: 0 5px;">至</div>
      <el-time-select
        v-model="endTime"
        style="width: 120px;"
        placeholder="结束时间"
        :picker-options="{
          start: getTimeSelectStartTime,
          step: step,
          end: end,
          minTime: startTime
        }"
      />
    </div>
  </div>
</template>
<script>
import dayjs from 'dayjs'
import Emitter from 'element-ui/lib/mixins/emitter'

export default {
  name: 'TimeDatePicker',
  mixins: [Emitter],
  props: {
    value: {
      type: [String, Array],
      default: ''
    },

    start: {
      type: String,
      default: '0:00'
    },

    end: {
      type: String,
      default: '23:59'
    },

    step: {
      type: String,
      default: '00:30'
    },

    /**
     * 是否实时变更开始时间
     * true 则从当前时间开始
     */
    isRealTime: {
      type: Boolean,
      default: false
    },

    datePickerOptions: {
      type: Object,
      default: () => ({})
    }

  },
  data() {
    return {
      date: '',
      startTime: '',
      endTime: '',
      selfChanging: false,
      isInternalUpdate: false
    }
  },
  computed: {
    getTimeSelectStartTime() {
      if (this.isRealTime) {
        return this.getRealTime()
      } else {
        return this.start
      }
    }
  },
  watch: {
    date(val) {
      if (this.isInternalUpdate) return
      this.startTime = ''
      this.endTime = ''
    },

    value: {
      immediate: true,
      handler(val) {
        if (this.selfChanging) {
          this.selfChanging = false
          return
        }
        this.initFromValue(val)
      }
    },

    startTime() {
      this.emitChange()
    },

    endTime() {
      this.emitChange()
    }
  },
  methods: {
    // 从value初始化内部状态
    initFromValue(val) {
      this.isInternalUpdate = true

      if (Array.isArray(val) && val.length === 2 && val[0] && val[1]) {
        const startParts = val[0].split(' ')
        const endParts = val[1].split(' ')

        this.date = startParts[0] || ''
        this.startTime = startParts[1] ? startParts[1].substring(0, 5) : ''
        this.endTime = endParts[1] ? endParts[1].substring(0, 5) : ''
      } else {
        this.date = ''
        this.startTime = ''
        this.endTime = ''
      }

      this.$nextTick(() => {
        this.isInternalUpdate = false
      })
    },

    emitChange() {
      let finalTime = []

      if (this.date && this.startTime && this.endTime) {
        finalTime = [
          `${this.date} ${this.startTime}:00`,
          `${this.date} ${this.endTime}:00`
        ]
      }

      // 标记为内部变化并更新value
      this.selfChanging = true
      this.$emit('input', finalTime)
      this.$emit('change', finalTime)

      // 触发Element表单验证
      this.dispatch('ElFormItem', 'el.form.change', finalTime)
    },

    getRealTime() {
      const now = dayjs()

      // 如果传入日期不是今天，返回固定时间 08:00
      if (this.date && dayjs(this.date).format('YYYY-MM-DD') !== now.format('YYYY-MM-DD')) {
        return '08:00'
      }

      // 解析 step 为分钟数
      const [stepHours, stepMinutes] = this.step.split(':').map(Number)
      const stepInMinutes = stepHours * 60 + stepMinutes

      if (stepInMinutes <= 0 || stepInMinutes > 1440) {
        throw new Error('Invalid time step')
      }

      // 获取当前时间从今天零点开始经过的分钟数
      const todayStart = now.startOf('day')
      const minutesSinceMidnight = now.diff(todayStart, 'minute')

      // 向上取整到最近的步长单位
      const stepsPassed = Math.floor(minutesSinceMidnight / stepInMinutes)
      const nextStepTime = todayStart.add(stepsPassed * stepInMinutes, 'minute')

      // 如果当前正好在步长点上，就加一步
      const resultTime =
        minutesSinceMidnight % stepInMinutes === 0
          ? nextStepTime.add(stepInMinutes, 'minute')
          : nextStepTime.add(stepInMinutes, 'minute')

      // 返回格式化后的时间字符串
      return resultTime.format('HH:mm')
    }
  }
}
</script>
<style lang="scss" scoped>
.time-date-picker {
  //align-items: center;

  .time-selector {
    margin-left: 10px;

  }
}

</style>
